package project.work;

import org.apache.log4j.Logger;

import project.controllers.ConsoleScanner;
import project.controllers.Messager;
import project.controllers.Printer;
import project.menu.Builder;
import project.menu.IMenu;
import project.menu.IMenuItem;
import project.menu.mainmenu.MainMenu;
import api.controller.IAutoservice;
import entitiesfactory.EntitiesFactory;

public class Navigator {

	private static Navigator NAVIGATOR;
	private Integer choice;
	private IMenu currentMenu;
	private IMenuItem currentMenuItem;
	private IAutoservice autoservice;
	private MainMenu mainManu;
	private ConsoleScanner console_scanner;
	private static final Logger log=Logger.getLogger(Navigator.class);
	private EntitiesFactory entities_factory=EntitiesFactory.getInstance();

	private Navigator() {
		mainManu = MainMenu.getInstance();
		console_scanner = ConsoleScanner.getInstance();
		autoservice=(IAutoservice) entities_factory.getObject(IAutoservice.class);
		

	}

	public static Navigator getInstance() {
		if (NAVIGATOR == null) {
			NAVIGATOR = new Navigator();
		}
		return NAVIGATOR;
	}

	public void navigation() {
		Builder.build();
		Printer.printMenu(mainManu.getMenu());
		currentMenu = mainManu;

		Printer.printMessage(Messager.MAKE_CHOICE);

		do {
			try {
				choice = console_scanner.getChoice();
				if (choice > (currentMenu.getMenu().size() - 1)) {
					Printer.printMessage(Messager.ERROR_CHOICE);
				}

				for (IMenuItem i : getCurrentMenu().getMenu()) {
					if (choice == i.getId()) {
						currentMenuItem = i;
						try{
							i.action(autoservice);
						} catch (RuntimeException e){
							Printer.printMessage(e.getMessage());
						}
					}
				}
			} catch (Exception e) {
				System.out.println(Messager.ERROR_CHOICE);
				log.warn(Messager.ERROR_CHOICE);
				
			}

		} while (currentMenuItem != mainManu.getMenu().get(4));
		Printer.printMessage(Messager.THANKS);

	}

	public void drawMenu(IMenu menu) {
		currentMenu = menu;
		Printer.printMessage(Messager.MAKE_CHOICE);
		Printer.printMenu(currentMenu.getMenu());
	}

	private IMenu getCurrentMenu() {
		return currentMenu;
	}

}